require('dotenv').config()
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const User = require('../models/user')

const loginRouter = require('express').Router()

loginRouter.post('/', async (req, response) => {
  const { username, password } = req.body
  const user = await User.findOne({ username })
  const passwordCorrect = user
    ? await bcrypt.compare(password, user.passwordHash)
    : false
  if (!(user && passwordCorrect)) {
    return response.json({
      msg: '用户名或密码错误',
      data: null,
      errno: 1,
    })
  }
  const uerForToken = {
    username: user.username,
    id: user._id,
  }
  const token = jwt.sign(uerForToken, process.env.SECRET, {
    expiresIn: '1d',
  })
  response.json({
    token,
    username,
    name: user.name,
  })
})

module.exports = loginRouter
